######################################################################################
#
# This file was provided as part of the SharePoint Mystery Deployment package
# Created by Christopher Kimbell (http://sharepointmystery.com)
#
######################################################################################

# -----------------------------------------------------------------
# Creates an object used to manipulate the Visio Graphics Service
# -----------------------------------------------------------------
function New-VisioService()
{
    $obj=new-object PSObject -Property @{
      Name = "Visio Graphics Service";
      Proxy = "Visio Graphics Service Proxy";
      Pool = New-ApplicationPool;
      Service = New-SupportingService;
      AddToDefaultGroup = $true;
    }
    $obj.Service.Name = "Visio Graphics Service"
    # -----------------------------------------------------------------
    # Validates the information in the object
    # -----------------------------------------------------------------
    Add-Method $obj "Validate" `
    {
        Write-Operation "Validating Visio Service"
        $this.Pool.Validate()
        $this.Service.Validate()
        Validate-NotEmpty "Name" $this.Name
        Validate-NotEmpty "Proxy" $this.Proxy
    }
    # -----------------------------------------------------------------
    # Provisions the Service
    # -----------------------------------------------------------------
    Add-Method $obj "Provision" `
    {
        $sa = Get-SPServiceApplication  | Where-Object {$_.DisplayName -eq $this.Name}

        if($sa -eq $null)
        {
            Write-Operation "Creating $($this.Name)"
            $pool = $this.Pool.Provision()
            $sa = New-SPVisioServiceApplication -Name $this.Name `
                    -ApplicationPool $pool `
                    -AddToDefaultGroup:$this.AddToDefaultGroup
        }
        else
        {
            Write-OperationDone "$($this.Name) has already been provisioned"  
        } 
         
        $proxy = Get-SPServiceApplicationProxy  | Where-Object {$_.DisplayName -eq $this.Proxy}  
        if($proxy -eq $null)
        {
            New-SPVisioServiceApplicationProxy -Name $this.Proxy -ServiceApplication $sa 
        }
        else
        {
            Write-OperationDone "$($this.Proxy) has already been provisioned"  
        }
        $this.Service.Provision()
    }
    # -----------------------------------------------------------------
    # Unprovisions the Service
    # -----------------------------------------------------------------
    Add-Method $obj "Unprovision" `
    {
        Remove-ServiceApplicationProxy $this.Proxy
        Remove-ServiceApplication $this.Name
        $this.Service.Unprovision()
    }
    return $obj
}
